package com.cyx.job.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyx.common.core.constants.CacheConstants;
import com.cyx.common.core.constants.Constants;
import com.cyx.common.core.enums.ExamListType;
import com.cyx.common.redis.service.RedisService;
import com.cyx.job.domain.Exam;
import com.cyx.job.mapper.ExamMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ExamXxlJob {

    private static final Logger log = LoggerFactory.getLogger(ExamXxlJob.class);
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler() {

        log.info("**************examListOrganizeHandler*******************");

        // 从数据库中查询未完赛的竞赛列表
        List<Exam> unfinshedExamList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .gt(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        // 刷新缓存（把未完赛的竞赛列表存储到redis中对应的list中）
        refreshCache(unfinshedExamList, CacheConstants.EXAM_UNFINISHED_LIST);
        // 从数据库中查询历史竞赛列表
        List<Exam> historyExamList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .le(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        // 刷新缓存（把历史竞赛列表存储到redis中对应的list中）
        refreshCache(historyExamList, CacheConstants.EXAM_HISTORY_LIST);
    }

    public void refreshCache(List<Exam> examList, String examListKey) {
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        // 遍历竞赛列表，将竞赛id和竞赛映射起来存储到map中
        // 并将id存储到list中
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        // 这里为什么要用multiSet（批量存储）
        // 因为从数据库中获取的竞赛列表中的竞赛可能不止一个，使用批量存储提高效率
        redisService.multiSet(examMap);  //刷新详情缓存
        // 为了防止重复数据，先清空redis中存储竞赛id的list
        redisService.deleteObject(examListKey);
        // 再使用尾插法重新存储数据
        redisService.rightPushAll(examListKey, examIdList);      //刷新列表缓存
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

}
